<template>
  <!-- 成果等级 -->
  <a-select v-bind="$attrs" v-on="$listeners" :placeholder="placeholder" v-model="currentValue" allowClear>
    <a-spin v-if="fetching" slot="notFoundContent" size="small" />
    <a-select-option v-else v-for="i in project" :key="i[replaceFields.key]" :value="i[replaceFields.key]">{{ i[replaceFields.name] }}</a-select-option>
  </a-select>
</template>
<script>
import { getGradeList } from '@/api/achievementsType'

export default {
  name:'SelectAchievementLevel',
  inheritAttrs: false,
  props: {
    // v-model绑定的数据
    value: {
      type: [Array, String, Object, Number],
    },
    // 需要联动的表单名，
    form: {
      type: Object,
      default: function () {
        return {}
      },
    },
    // placeholder
    placeholder:{
      type: String,
      default: function () {
        return '请选择'
      },
    },
    // 需要联动的表单名
    keyValue: {
      type: String,
      default: function () {
        return 'achievementsType'
      },
    },
    // 联动表单值改变时是否清空当前表单值
    isClear: {
      type: Boolean,
      default() {
        return true
      },
    },
    // 是否获取全部列表（包括停用项）
    isAll: {
      type: Boolean,
      default() {
        return true
      },
    },
    replaceFields: {
      type: Object,
      default() {
        return {
          key: 'id',
          name: 'levelName',
        }
      },
    },
  },
  data() {
    return {
      fetching: false,
      project: [],
    }
  },
  methods: {
    getGradeList(params) {
      this.fetching = true
      if (!this.isAll) {
        params.status = '1'
      }
      getGradeList(params)
        .then((res) => {
          this.fetching = false
          if (res.code === 200) {
            this.project = res.data.data
          } else {
            this.$message.error('err:', res.message)
          }
        })
        .catch((res) => {
          this.fetching = false
        })
    },
    // 获取指定项目的name
    getValueName(id) {
      const target = this.project.find((item) => item.code === id)
      return (target && target.name) || void 0
    },
  },
  computed: {
    // 需要联动的表单值
    attr() {
      // console.log(this.form[this.keyValue])
      return this.form[this.keyValue]
    },
    // 转换绑定的选中数据，与v-model同步
    currentValue: {
      get: function () {
        return this.value
      },
      set: function (value) {
        this.$emit('input', value)
      },
    },
  },
  watch: {
    // 监听联动表单值重置项目列表
    attr(val) {
      // 清空表单
      if (this.isClear) {
        this.currentValue = ''
      }
      // 重置列表
      this.project = []
      val && this.getGradeList({ typeId: val })
    },
  },
}
</script>
